package com.yanfan.ccapicode.handler.action;

import com.alibaba.fastjson2.JSONObject;
import com.yanfan.ccapicode.bean.info.AccessTokenInfo;
import com.yanfan.ccapicode.bean.info.ActionContext;
import com.yanfan.ccapicode.bean.info.ThirdPartyCloudConfigInfo;
import com.yanfan.ccapicode.bean.third.baidu.BaiduHeader;
import com.yanfan.ccapicode.bean.third.baidu.BaiduStandardRequest;
import com.yanfan.ccapicode.enums.ThirdPartyCloudEnum;
import com.yanfan.ccapicode.handler.factory.CloudCloudHandlerFactory;
import com.yanfan.ccapicode.handler.factory.CloudProtocolHandlerFactory;
import com.yanfan.ccapicode.handler.protocol.AbstractStrategyProtocolHandler;
import com.yanfan.ccapicode.mangaer.AccessTokenManager;
import com.yanfan.ccapicode.service.ThirdPartyConfigService;
import org.springframework.stereotype.Service;

/**
 * :)
 *
 */
@Service
public class BaiduCloudHandler extends AbstractCloudCloudHandler {

    protected BaiduCloudHandler(CloudCloudHandlerFactory factory, CloudProtocolHandlerFactory protocolFactory, AccessTokenManager accessTokenManager, ThirdPartyConfigService thirdPartyConfigService) {
        super(factory, protocolFactory, accessTokenManager, thirdPartyConfigService);
    }

    @Override
    protected String getAccessToken(String request) {
        //获取token
        BaiduStandardRequest baiduStandardRequest = JSONObject.parseObject(request, BaiduStandardRequest.class);
        return baiduStandardRequest.getPayload().getAccessToken();
    }

    @Override
    protected String dispatchHandler(String request, AccessTokenInfo accessToken) {
        BaiduStandardRequest baiduStandardRequest = JSONObject.parseObject(request, BaiduStandardRequest.class);
        ThirdPartyCloudConfigInfo config = thirdPartyConfigService.getConfig(accessToken.getClientId());

        BaiduHeader header = baiduStandardRequest.getHeader();
        //根据namespace调用处理器
        String namespace = header.getNamespace();
        AbstractStrategyProtocolHandler cloudProtocolHandler = protocolFactory.getStrategy(namespace, AbstractStrategyProtocolHandler.class);
        Object action = cloudProtocolHandler.action(request, new ActionContext(accessToken, config));
        return JSONObject.toJSONString(action);
    }

    @Override
    protected void extraAction(String request) {
    }

    @Override
    public String getKey() {
        return ThirdPartyCloudEnum.BAIDU.name();
    }
}
